package com.common.app.utls.pay

import android.app.Activity
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import com.alipay.sdk.app.PayTask
import com.common.app.data.bean.AliPayResult
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.PayBean
import com.common.app.data.bean.PayResult
import com.common.app.data.bean.PayStatus
import com.common.app.data.bean.PayType
import com.common.base.utils.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus

/**
 * 支付工具类
 */
class PayHelper(val activity: Activity?) {

    companion object {
        private const val SDK_PAY_FLAG = 1
        var TAG = PayHelper::class.java.simpleName

        class MyHandler : Handler() {

            override fun handleMessage(msg: Message) {
                when (msg?.what) {
                    SDK_PAY_FLAG -> {
                        val payResult =
                            AliPayResult(msg.obj as Map<String, String>)

                        /**
                         * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                         */
                        val resultStatus = payResult.resultStatus
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知
                            LiveEventBus.get(KeyEvents.KEY_PAY_RESULT, PayResult::class.java).post(PayResult(
                                PayType.ALIPAY, PayStatus.SUCCESS))
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            LiveEventBus.get(KeyEvents.KEY_PAY_RESULT, PayResult::class.java).post(PayResult(PayType.ALIPAY, PayStatus.CANCEL))
                        } else {
                            LiveEventBus.get(KeyEvents.KEY_PAY_RESULT, PayResult::class.java).post(PayResult(PayType.ALIPAY, PayStatus.FAILED))
                        }
                    }
                }
            }
        }
    }

    private val mHandler = MyHandler()

    fun toPay(data: PayBean) {
        when (data.payType) {
            PayType.WECHAT -> {
                WXPayUtils.pay(data.wxPayData)
            }
            PayType.ALIPAY -> aliPay(data.aliPayData)
        }
    }


    private fun aliPay(orderInfo: String) {
        val payRunnable = Runnable {
            val aliPay = PayTask(activity)
            val result = aliPay.payV2(orderInfo, true)
            LogUtils.e(TAG, "alipay Result: $result")

            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }
}